// 防抖
/**
 * @param fn 需要执行的函数代码
 * @param delay 防抖间隙(默认：600ms)
 * @param immediate 函数是否立即执行一次
 * @param callBack 执行完后的回调函数
 */
export function debounce(fn: any, delay = 600, immediate = false, callBack: any) {
  let timer = null;
  let isInvoke = false;

  // eslint-disable-next-line func-names
  const _debounce = function (...args: any[]) {
    if (timer) clearTimeout(timer);

    if (immediate && !isInvoke) {
      const result = fn.apply(this, args);
      if (callBack) callBack(result);
      isInvoke = true;
    } else {
      timer = setTimeout(() => {
        const result = fn.apply(this, args);
        if (callBack) callBack(result);
        isInvoke = false;
      }, delay);
    }
  };

  _debounce.cancel = () => {
    if (timer) clearTimeout(timer);
    timer = null;
    isInvoke = false;
  };

  return _debounce;
}

/**
 * @param fn 需要执行的函数代码
 * @param interval 节流间隙(默认：600ms)
 * @param config leading:函数第一次是否执行 trailing:最后一次没到达节流间隙也触发执行
 */
export function throttle(fn: any, interval = 600, config = { leading: true, trailing: false }) {
  let timer = null;
  let lastTime = 0;
  const { leading, trailing } = config;

  function _throttle(...args: any[]) {
    const nowTime = new Date().getTime();
    if (!leading && !lastTime) lastTime = nowTime;
    const remainTime = interval - (nowTime - lastTime);

    if (remainTime <= 0) {
      if (timer) {
        clearTimeout(timer);
        timer = null;
      }
      fn.apply(this, args);
      lastTime = nowTime;
    } else if (!timer && trailing) {
      timer = setTimeout(() => {
        fn.apply(this, args);
        lastTime = new Date().getTime();
        timer = null;
      }, remainTime);
    }
  }

  _throttle.clear = () => {
    if (timer) clearTimeout(timer);
    timer = null;
    lastTime = 0;
  };

  return _throttle;
}
// 转换日期方法
export function formatDate(t: any) {
  const date = new Date(t);
  const YY = `${date.getFullYear()}`;
  const MM = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : `${date.getMonth() + 1}`;
  const DD = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate();
  const time = `${YY}-${MM}-${DD}`;
  return time;
}
